<template>
    <div class="page-box">
        <div class="qr-container">
            <div class="qr-box">
                <div id="reader"></div>
            </div>
        </div>
        <div class="btn-box">
            <div>
                <Icon name="arrow-left" @click="clickBack" />
            </div>
            <div>
                <Uploader v-model="state.fileList" :preview-image="false" :after-read="uploadImg">
                    <Icon name="photo-o" />
                </Uploader>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { reactive, onMounted, onUnmounted } from "vue";
import { Html5Qrcode } from "html5-qrcode";
import { showToast, Uploader, Icon, showDialog } from "vant";
import { useRoute, useRouter } from "vue-router";
import { Http } from "@b/model/base/http";
import { navBarStore } from "@b/store";

const snavBarStore = navBarStore()
const router = useRouter();
const route = useRoute()

const TargetUrl = route.query.url
const title = route.query.title

onMounted(() => {
    if (title)
        snavBarStore.setNavBar(title as string, 0)
})

const state: any = reactive({
    html5QrCode: null,
    fileList: [],
});

onMounted(() => {
    getCamerasInfo();
});
onUnmounted(() => {
    if (state.html5QrCode?.isScanning) {
        stopScan();
    }
});

const clickBack = () => {
    router.back()
};

const getCamerasInfo = () => {
    Html5Qrcode.getCameras()
        .then((devices) => {
            if (devices && devices.length) {
                state.html5QrCode = new Html5Qrcode("reader");
                startScan();
            }
        })
        .catch(() => {
            showToast({
                message: "摄像头无访问权限！",
                duration: 2000,
            });
        });
};

const startScan = () => {
    state.html5QrCode
        .start(
            { facingMode: "environment" },
            {
                fps: 1,
                qrbox: { width: 250, height: 250 },
            },
            async (decodedText: string) => {
                try {
                    const url = new URL(decodedText)
                    showDialog({
                        title: '成功',
                        message: '扫码成功，是否前往绑定',
                    }).then(() => {
                        router.replace(TargetUrl + url.search)
                    })
                } catch (err) {
                    console.log(err)
                    const StoreItemId = Number(TargetUrl)
                    if (!isNaN(StoreItemId)) {
                        const res = await new Http().request(`/v2/coupon/verification?id=${decodedText}&StoreItemId=${TargetUrl}`)
                        if (res) {
                            showToast('核销成功')
                            router.back()
                        }
                    } else {
                        showToast('核销商品为空')
                    }
                }
            }
        )
        .catch((err: any) => {
            console.log("扫码失败", err);
        });
};

const stopScan = () => {
    state.html5QrCode
        .stop()
        .then((a: any) => {
            console.log("已停止扫码", a);
        })
        .catch((err: any) => {
            console.log(err);
            showToast("停止失败");
        });
};

const uploadImg = () => {
    try {
        (window as any).qrcode.callback = (result: any) => {
            showToast(result);
        };
        const file = state.fileList[0].file;
        const reader = new FileReader();
        reader.onload = (function () {
            return function (e) {
                (window as any).qrcode.decode(e.target?.result);
            };
        })();
        reader.readAsDataURL(file);
    } catch (error) {
        console.log(error);
        showToast({
            message: "识别失败！",
            duration: 2000,
        });
    }
};
</script>
<style scoped>
.page-box {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #000;
}

.qr-container {
    position: relative;
    width: 100%;
    height: 90%;
}

.qr-box {
    height: 100%;
}

#reader {
    top: 50%;
    left: 0;
}

.btn-box {
    flex: 1;
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
    margin-top: auto;
    padding: 12px;
    color: var(--van-background);
    font-size: 28px;
}
</style>